package com.fleafinder;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.fleafinder.entity.Category;
import com.fleafinder.entity.MarketType;

public class CategoryListFragment extends ListFragment {
	
	private TextView tvMarketType = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.category_list_fragment,
				container, false);
		
		tvMarketType = (TextView)view.findViewById(R.id.market_type);
		
		while(DataCenter.getInstance().getMarketCategoryList() == null || DataCenter.getInstance().getMarketCategoryList().isEmpty())
		{
			try {
				Thread.sleep(CommonConstants.DEFAULT_SLEEP_TIME);
			} catch (Exception ex) {
				Log.d("exception", ex.getMessage());
			}
		}
		ArrayAdapter<Category> adapter = new ListViewMarketCategoryAdapter(
				this.getActivity(), DataCenter.getInstance().getMarketCategoryList());

		setListAdapter(adapter);
		
		updateMarketTypeTitle();
		
		return view;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		
		//each call to DataCenter.getInstance() run a check, so create a variable
		//to avoid many checks run.
		String tag = CommonConstants.HOME_FRAGMENT;
		DataCenter dc = DataCenter.getInstance();
		dc.setRootFragmentOfTab(false);
		TextView textView = (TextView) v.findViewById(R.id.textView_category);
		if (textView != null) {
			Integer categoryId = (Integer) textView.getTag();
			if (categoryId != -1) {
				dc.setCurrentMarketListMode(
						CommonConstants.MARKETTYPE_AND_CATEGORY);
				dc.setSelectedMaketCategory(categoryId);
			} else {
				dc.setCurrentMarketListMode(
						CommonConstants.MARKETTYPE_AND_VISALLE);
			}
			FragmentActivity activity = (FragmentActivity) v.getContext();
			FragmentManager fm = activity.getSupportFragmentManager();
			FragmentTransaction transaction = fm.beginTransaction();
			transaction.replace(R.id.fragment_placeholder, dc.getMarketListFragment(),tag);
			transaction.addToBackStack(tag);
			transaction.commit();
		}
	}
	
	public void updateMarketTypeTitle(){
		if(tvMarketType != null){
			DataCenter dc = DataCenter.getInstance();
			for(MarketType mt : dc.getMarketTypeList()){
				if(mt.getMarketId() == dc.getSelectedMarketTypeId()){
					tvMarketType.setText(mt.getMarketTypeName());
					break;
				}
			}
		}
	}
}
